# -*- coding: utf-8 -*-
"""
@Time ： 2021/5/13 15:16
@Auth ： Mr. royalday 2487625775
@Company ：XXX
@Function ：离线-腾讯云对象存储服务
"""
# appid 已在配置中移除,请在参数 Bucket 中带上 appid。Bucket 由 BucketName-APPID 组成
# 1. 设置用户配置, 包括 secretId，secretKey 以及 Region
import os

import django
from qcloud_cos import CosConfig
from qcloud_cos import CosS3Client
from django.conf import settings
import sys
import logging
import time
from base_url import current_path
sys.path.append(current_path)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tracer.settings")
django.setup()  # os.environ['DJANGO_SETTINGS_MODULE']


def init_cos(secret_id="", secret_key="", region=""):
    """
    初始化，创建对象存储客户端对象
    :param secret_id:
    :param secret_key:
    :param region:
    :return:
    """
    if secret_id is "" or secret_id is None:
        secret_id = settings.TENCENT_COS['secret_id']  # 替换为用户的 secretId
    if secret_key is "" or secret_key is None:
        secret_key = settings.TENCENT_COS['secret_key']  # 替换为用户的 secretKey
    if region is "" or region is None:
        region = settings.TENCENT_COS['region']  # 替换为用户的 Region, 区域名称

    logging.basicConfig(level=logging.INFO, stream=sys.stdout)
    token = None  # 使用临时密钥需要传入 Token，默认为空，可不填
    scheme = 'https'  # 指定使用 http/https 协议来访问 COS，默认为 https，可不填

    proxies = {
        'http': '127.0.0.1:80',  # 替换为用户的 HTTP代理地址
        'https': '127.0.0.1:443'  # 替换为用户的 HTTPS代理地址
    }

    endpoint = 'cos.accelerate.myqcloud.com'  # 替换为用户的 endpoint

    # domain 自定义域名，通常不用设置，如果使用全球加速域名，则设置成对应的域名，例如 examplebucket-1250000000.cos.accelerate.myqcloud.com，
    # 开启全球加速请参考 https://cloud.tencent.com/document/product/436/38864
    domain = 'examplebucket-1250000000.cos.accelerate.myqcloud.com'

    config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key, Token=token, Scheme=scheme)
    # 2. 获取客户端对象
    client = CosS3Client(config)
    # 参照下文的描述。或者参照 Demo 程序，详见 https://github.com/tencentyun/cos-python-sdk-v5/blob/master/qcloud_cos/demo.py
    return client


def create_bucket(bucketName):
    """
    创建桶
    :param bucketName: 同名称
    :return:
    """
    appid = settings.TENCENT_COS['appid']  # 替换为用户的 appid
    time_stamp = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime())
    bucketName = str(bucketName) + "-" + time_stamp + '-' + appid
    client = init_cos()

    response = client.create_bucket(
        Bucket=bucketName,
        ACL="public-read"  # private 私有的只能自己读写  /  public-read 公有读私有写 / public-read-write 公有读写
    )
    return response


def upload_file(bucketName, localFilePath, key):
    """
    上传文件到cos对象存储
    :param bucketName: 桶名称
    :param localFilePath: 本地文件路径
    :param key: 上传到桶后的文件名称
    :return:
    """
    client = init_cos()
    response = client.upload_file(
        Bucket=bucketName,
        LocalFilePath=localFilePath,
        Key=key,
        PartSize=1,
        MAXThread=10,
        EnableMD5=False
    )
    print(response['ETag'])


if __name__ == '__main__':
    #  print(create_bucket(bucketName="test"))
    localFile = r'C:\Users\royalday\Pictures\Camera Roll\御天.png'
    upload_file(bucketName='test2021-05-13-16-42-11-1305644719', localFilePath=localFile, key='御天.png')
